package com.example.myapplication3.message

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication3.Msg
import com.example.myapplication3.R

class MsgAdapter(val msgList: List<Msg>): RecyclerView.Adapter<RecyclerView.ViewHolder> (){

    inner class LeftViewHolder(view: View): RecyclerView.ViewHolder(view){
        val leftMsg: TextView = view.findViewById(R.id.leftMsg)
    }
    inner class RightViewHolder(view: View): RecyclerView.ViewHolder(view){
        val rightMsg: TextView = view.findViewById(R.id.rightMsg)
    }
    // 重写 getItemViewType，返回当前消息的布局类型
    override fun getItemViewType(position: Int): Int {
        // 根据当前 position 的 Msg 类型，返回对应的布局类型
        return msgList[position].type
    }

    // 根据布局类型创建对应的 ViewHolder（左/右）
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ) = if (viewType == Msg.TYPE_RECEIVED){
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.msg_left_item,parent,false)
        LeftViewHolder(view)
    }else {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.msg_right_item,parent,false)
        RightViewHolder(view)
    }

    override fun onBindViewHolder(
        holder: RecyclerView.ViewHolder,
        position: Int
    ) {
        val  msg = msgList[position]
        when(holder){
            is LeftViewHolder -> holder.leftMsg.text = msg.content
            is RightViewHolder -> holder.rightMsg.text = msg.content
            else -> throw IllegalArgumentException()
        }
    }

    override fun getItemCount() = msgList.size

}